extends CanvasLayer

@onready var textEdit:TextEdit = $TextEdit


func _ready():
	hide()
	
	textEdit.text_changed.connect(onTextChanged)
	

func _exit_tree():
	textEdit.text_changed.disconnect(onTextChanged)
	

func onTextChanged():
	var text = textEdit.text
	
	# 移除不需要的字符
	text = text.replace("\r", "")  # 移除回车符
	text = text.replace("\n", "")  # 移除换行符
	text = text.replace("\r\n", "")  # 移除回车换行符
	text = text.replace("`", "")   # 移除反引号
	
	# 更新文本
	if text != textEdit.text:
		textEdit.text = text


func _physics_process(delta):
	processSwitchConsole()
	processConfirm()
	

func processConfirm():
	if Input.is_action_just_pressed("Confirm") and visible:
		call_deferred("onConfirm")
		

func onConfirm():
	executeCommand(textEdit.text)
	hideConsole()


func processSwitchConsole():
	if Input.is_action_just_pressed("Console"):
		if not visible:
			showConsole()
		else:
			hideConsole()
	
	
func showConsole():
	show()
	textEdit.text = ""
	GlobalData.playerAcceptMoveInput = false
	textEdit.grab_focus()
	

func hideConsole():
	hide()
	GlobalData.playerAcceptMoveInput = true
	textEdit.release_focus()
			
			
func executeCommand(cmd):
	var result = Global.parseSequenceCommand(cmd)
	if not result.has("methodName"):
		print("console command invalid")
		return
		
	var methodName = result.methodName 
	var params = result.params
	
	if CommandExecuter.has_method(methodName):
		CommandExecuter.call(methodName, params)
	else:
		print("No method handler methodName: ", methodName)
	
	
